package com.sh.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sh.common.ResponseInfoEnum;
import com.sh.common.ReturnVO;
import com.sh.entity.Customer;
import com.sh.entity.SystemParam;
import com.sh.entity.User;
import com.sh.service.CustomerService;
import com.sh.util.DateUtil;
import com.sh.util.ExcelUtil;
import com.sh.util.FileUitl;

import cn.hutool.core.util.NumberUtil;

/**
 *  客户 相关 controller
 * */
@RestController
@RequestMapping("/api/customer")
public class CustomerController extends BaseController{


	@Autowired
	CustomerService customerService;

	@ResponseBody
	@RequestMapping("/listCustomer")
	public ReturnVO listCustomer(
			@RequestParam(value = "startPage",required = false,defaultValue="1") int startPage,
			@RequestParam(value = "pageCount",required = false,defaultValue="100") int pageCount,
			@RequestParam(value = "customerName",required = false) String customerName){


		User user = getLoginUser();
		String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");
		Map<String,Object> conMap = new HashMap<String,Object>();
		conMap.put("customerName",customerName);

		//分页 开始  //返回数量  pageCount
		int start = (startPage-1)*pageCount;

		conMap.put("start", start);
		conMap.put("pageCount", pageCount);

		int count =
				customerService.listCustomerCount(conMap,user,sysTime);

		List<Customer> list =
				customerService.listCustomerByPage(conMap,user,sysTime);

		return succForPage(ResponseInfoEnum.CUSTOMER_QUERY_SUCCESS, list,count);

	}
	//上传 excel文件,并且到DB
	@ResponseBody
	@RequestMapping("/uploadCustomer")
	public ReturnVO uploadCustomer(MultipartFile file){

		User user = getLoginUser();
		SystemParam rootNode = null;
		try {
			if(!file.isEmpty()){
				String path = FileUitl.createFile(file,serverPath);
				List<List<Object>> list =
						ExcelUtil.readExcelFirstSheet(path);


				//检验数据的准确性，并转换为  List<Object> 格式
				Map<String,Object> map =
						checkDataAndToBO(list);

				String msg = (String)map.get("msg");
				if("".equals(msg)){
					//没有错误继续执行下面步骤
					List<Customer> checkList = (List<Customer>)map.get("list");
					String sysTime = DateUtil.getSysTime("yyyy-MM-dd hh:mm:ss");
					String rntMsg =
							customerService.saveUpload(checkList,user,sysTime);
				}else{
					//有错误
					return failForService("400", ResponseInfoEnum.CUSTOMER_UPLOAD_FAILED,msg);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("读取文件错误:",e);
			return failForService("400", ResponseInfoEnum.CUSTOMER_UPLOAD_FAILED,e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("上传文件错误:",e);
			return failForService("400", ResponseInfoEnum.CUSTOMER_UPLOAD_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.CUSTOMER_UPLOAD_SUCCESS, null);

	}

	//检验数据的准确性，并转换为  List<Stone> 格式
	private Map<String,Object> checkDataAndToBO(List<List<Object>> list) {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String,Object>();

		//当前月
		String curMonth = DateUtil.getSysTime("yyyy-MM");

		StringBuffer sb = new StringBuffer();
		sb.append("");
		List<Customer> objList = new ArrayList<Customer>();
		for(int i=0;i<list.size();i++){
			List<Object> listTmp = list.get(i);
			Customer obj = new Customer();

			//客户名称
			obj.setCustomerName((String)listTmp.get(0));

			//客户类型
			obj.setType((String)listTmp.get(1));

			//期初金额
			obj.setInitAmount((String)listTmp.get(2));

			//备注
			obj.setRemark((String)listTmp.get(3));

			String msg = checkData(obj);
			if(!"".equals(msg)){
				sb.append("第 "+(i+1)+"行数据："+msg + "\n");
			}


			objList.add(obj);
		}

		map.put("msg", sb.toString());
		map.put("list", objList);
		return map;
	}


	/**
	 * 批量 删除 客户 信息
	 * 删除之前需要 进行 数据验证是不是 当年数据，如果是当前数据，才能修改
	 * */
	@ResponseBody
	@RequestMapping("/deleteCustomers")
	public ReturnVO deleteCustomers(
			@RequestParam(value = "tableSelectedIds",required = false) String tableSelectedIds
	){

		User user = getLoginUser();
		try {

			if(tableSelectedIds!=null){
				String[] ids = tableSelectedIds.split(",");
				customerService.deleteCustomers(ids);
			}


		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("删除 错误:",e);
			return failForService("400", ResponseInfoEnum.CUSTOMER_DELETE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.CUSTOMER_DELETE_SUCCESS, null);

	}

	/**
	 * 新增 / 修改 保存数据
	 * */
	@ResponseBody
	@RequestMapping("/saveCustomers")
	public ReturnVO saveCustomers(
			Customer customer
	){

		User user = getLoginUser();
		try {
			Map<String,Object> conMap = new HashMap<String,Object>();
			conMap.put("customer", customer);
			conMap.put("user", user);

			//添加验证
			String msg = checkData(customer);
			if(!"".equals(msg)){
				return failForService("400", ResponseInfoEnum.CUSTOMER_SAVE_FAILED,msg);
			}

			customerService.saveCustomers(customer,user);


		}catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("保存 错误:",e);
			return failForService("400", ResponseInfoEnum.CUSTOMER_SAVE_FAILED,e.getMessage());
		}
		return succForService(ResponseInfoEnum.CUSTOMER_SAVE_SUCCESS, null);

	}
	//添加验证
	private String checkData(Customer customer) {
		// TODO Auto-generated method stub

		StringBuffer msg = new StringBuffer();
		msg.append("");

		//客户名称不能为空
		if("".equals(customer.getCustomerName())){
			msg.append("【客户名称】不能为空! ");
		}else{
			//判断 客户名称有么有存在
			boolean flag =
					customerService.isCustomerExist(customer);
			if(flag){
				msg.append("【客户名称】已经存在! ");
			}
		}

		//判断 客户类型必须为 J或者D
		if("".equals(customer.getType())){
			msg.append("【客户类型】不能为空! ");
		}else{
			if(!"J".equals(customer.getType()) &&
					!"D".equals(customer.getType())){
				msg.append("【客户类型】只能为J 或者 D! ");
			}
		}

		//判断 初始金额必须为 J或者D
		if("".equals(customer.getInitAmount())){
			msg.append("【初始金额】不能为空! ");
		}else{
			if(!NumberUtil.isNumber(customer.getInitAmount())){
				msg.append("【初始金额】只能为 数字! ");
			}
		}

		return msg.toString();
	}




}
